<template>
  <div class="news-detail-container">
    <div class="page-header">
      <div class="header-left">
        <el-button icon="ArrowLeft" @click="goBack">返回</el-button>
        <h1>新闻详情</h1>
      </div>
      <div class="header-right">
        <el-button @click="editNews">编辑新闻</el-button>
        <el-dropdown @command="handleNewsAction">
          <el-button type="primary">
            操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="publish" v-if="news.status === 'draft'">发布新闻</el-dropdown-item>
              <el-dropdown-item command="unpublish" v-if="news.status === 'published'">撤回新闻</el-dropdown-item>
              <el-dropdown-item command="top" v-if="!news.isTop">置顶</el-dropdown-item>
              <el-dropdown-item command="untop" v-if="news.isTop">取消置顶</el-dropdown-item>
              <el-dropdown-item command="recommend" v-if="!news.isRecommend">推荐</el-dropdown-item>
              <el-dropdown-item command="unrecommend" v-if="news.isRecommend">取消推荐</el-dropdown-item>
              <el-dropdown-item command="duplicate">复制新闻</el-dropdown-item>
              <el-dropdown-item command="delete" divided>删除新闻</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <div class="news-content">
      <el-row :gutter="20">
        <!-- 新闻内容 -->
        <el-col :span="16">
          <el-card>
            <div class="news-article">
              <div class="article-header">
                <h2 class="article-title">{{ news.title }}</h2>
                <div class="article-meta">
                  <el-tag :type="getStatusType(news.status)">
                    {{ getStatusText(news.status) }}
                  </el-tag>
                  <el-tag v-if="news.isTop" type="danger" size="small">置顶</el-tag>
                  <el-tag v-if="news.isRecommend" type="warning" size="small">推荐</el-tag>
                  <span class="author">作者：{{ news.authorName }}</span>
                  <span class="category">分类：{{ news.categoryName }}</span>
                  <span class="publish-time">发布时间：{{ formatTime(news.publishTime) }}</span>
                </div>
              </div>
              
              <div class="article-cover" v-if="news.cover">
                <img :src="news.cover" :alt="news.title" />
              </div>
              
              <div class="article-summary" v-if="news.summary">
                <h3>摘要</h3>
                <p>{{ news.summary }}</p>
              </div>
              
              <div class="article-content">
                <div v-html="news.content"></div>
              </div>
              
              <div class="article-tags" v-if="news.tags && news.tags.length">
                <h3>标签</h3>
                <el-tag 
                  v-for="tag in news.tags"
                  :key="tag"
                  size="small"
                  style="margin-right: 8px; margin-bottom: 8px;"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </el-card>

          <!-- 评论管理 -->
          <el-card title="评论管理" style="margin-top: 20px">
            <div class="comments-management">
              <div class="comments-toolbar">
                <el-button @click="refreshComments">刷新</el-button>
                <el-button @click="batchDeleteComments" :disabled="selectedComments.length === 0">
                  批量删除
                </el-button>
                <el-select v-model="commentFilter" @change="loadComments" style="width: 150px;">
                  <el-option label="全部评论" value="all" />
                  <el-option label="待审核" value="pending" />
                  <el-option label="已通过" value="approved" />
                  <el-option label="已拒绝" value="rejected" />
                </el-select>
              </div>
              
              <el-table 
                :data="comments" 
                v-loading="loadingComments"
                @selection-change="handleCommentSelection"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column label="用户" width="150">
                  <template #default="{ row }">
                    <div class="user-info">
                      <el-avatar :src="row.userAvatar" :size="32" />
                      <span>{{ row.username }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="content" label="评论内容" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getCommentStatusType(row.status)">
                      {{ getCommentStatusText(row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="评论时间" width="180">
                  <template #default="{ row }">
                    {{ formatTime(row.createTime) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                  <template #default="{ row }">
                    <el-button 
                      size="small" 
                      type="success" 
                      @click="approveComment(row)"
                      v-if="row.status === 'pending'"
                    >
                      通过
                    </el-button>
                    <el-button 
                      size="small" 
                      type="warning" 
                      @click="rejectComment(row)"
                      v-if="row.status === 'pending'"
                    >
                      拒绝
                    </el-button>
                    <el-button size="small" type="danger" @click="deleteComment(row)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-col>

        <!-- 侧边栏信息 -->
        <el-col :span="8">
          <!-- 统计信息 -->
          <el-card title="统计信息">
            <div class="stats-list">
              <div class="stat-item">
                <span class="stat-label">阅读量：</span>
                <span class="stat-value">{{ newsStats.viewCount || 0 }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">点赞数：</span>
                <span class="stat-value">{{ newsStats.likeCount || 0 }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">评论数：</span>
                <span class="stat-value">{{ newsStats.commentCount || 0 }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">分享数：</span>
                <span class="stat-value">{{ newsStats.shareCount || 0 }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">收藏数：</span>
                <span class="stat-value">{{ newsStats.favoriteCount || 0 }}</span>
              </div>
            </div>
          </el-card>

          <!-- 新闻信息 -->
          <el-card title="新闻信息" style="margin-top: 20px">
            <div class="news-info">
              <div class="info-item">
                <span class="label">新闻ID：</span>
                <span class="value">{{ news.id }}</span>
              </div>
              <div class="info-item">
                <span class="label">创建时间：</span>
                <span class="value">{{ formatTime(news.createTime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">更新时间：</span>
                <span class="value">{{ formatTime(news.updateTime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">发布时间：</span>
                <span class="value">{{ formatTime(news.publishTime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">来源：</span>
                <span class="value">{{ news.source || '原创' }}</span>
              </div>
              <div class="info-item">
                <span class="label">排序权重：</span>
                <span class="value">{{ news.sortOrder || 0 }}</span>
              </div>
            </div>
          </el-card>

          <!-- 相关新闻 -->
          <el-card title="相关新闻" style="margin-top: 20px">
            <div class="related-news">
              <div 
                v-for="relatedNews in relatedNewsList"
                :key="relatedNews.id"
                class="related-item"
                @click="viewRelatedNews(relatedNews.id)"
              >
                <img :src="relatedNews.cover" :alt="relatedNews.title" class="related-cover" />
                <div class="related-info">
                  <div class="related-title">{{ relatedNews.title }}</div>
                  <div class="related-time">{{ formatTime(relatedNews.publishTime) }}</div>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 操作日志 -->
          <el-card title="操作日志" style="margin-top: 20px">
            <div class="operation-logs">
              <el-timeline size="small">
                <el-timeline-item
                  v-for="log in operationLogs"
                  :key="log.id"
                  :timestamp="formatTime(log.createTime)"
                  size="small"
                >
                  <div class="log-content">
                    <div class="log-action">{{ log.action }}</div>
                    <div class="log-operator">操作人：{{ log.operatorName }}</div>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getNewsDetail,
  getNewsStats,
  getNewsComments,
  getRelatedNews,
  getOperationLogs,
  publishNews,
  unpublishNews,
  topNews,
  untopNews,
  recommendNews,
  unrecommendNews,
  deleteNews,
  approveComment as apiApproveComment,
  rejectComment as apiRejectComment,
  deleteComment as apiDeleteComment
} from '@/api/news'
import { formatTime } from '@/utils'

const route = useRoute()
const router = useRouter()

// 响应式数据
const news = ref({})
const newsStats = ref({})
const comments = ref([])
const relatedNewsList = ref([])
const operationLogs = ref([])
const selectedComments = ref([])
const commentFilter = ref('all')
const loadingComments = ref(false)

// 页面加载
onMounted(async () => {
  await loadNewsDetail()
  await loadNewsStats()
  await loadComments()
  await loadRelatedNews()
  await loadOperationLogs()
})

// 加载新闻详情
const loadNewsDetail = async () => {
  try {
    const response = await getNewsDetail(route.params.id)
    if (response.code === 200) {
      news.value = response.data
    }
  } catch (error) {
    console.error('获取新闻详情失败:', error)
    ElMessage.error('获取新闻详情失败')
  }
}

// 加载统计数据
const loadNewsStats = async () => {
  try {
    const response = await getNewsStats(route.params.id)
    if (response.code === 200) {
      newsStats.value = response.data
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 加载评论
const loadComments = async () => {
  try {
    loadingComments.value = true
    const response = await getNewsComments(route.params.id, { status: commentFilter.value })
    if (response.code === 200) {
      comments.value = response.data || []
    }
  } catch (error) {
    console.error('获取评论失败:', error)
  } finally {
    loadingComments.value = false
  }
}

// 加载相关新闻
const loadRelatedNews = async () => {
  try {
    const response = await getRelatedNews(route.params.id)
    if (response.code === 200) {
      relatedNewsList.value = response.data || []
    }
  } catch (error) {
    console.error('获取相关新闻失败:', error)
  }
}

// 加载操作日志
const loadOperationLogs = async () => {
  try {
    const response = await getOperationLogs(route.params.id)
    if (response.code === 200) {
      operationLogs.value = response.data || []
    }
  } catch (error) {
    console.error('获取操作日志失败:', error)
  }
}

// 新闻操作处理
const handleNewsAction = async (command) => {
  switch (command) {
    case 'publish':
      await publishNewsAction()
      break
    case 'unpublish':
      await unpublishNewsAction()
      break
    case 'top':
      await topNewsAction()
      break
    case 'untop':
      await untopNewsAction()
      break
    case 'recommend':
      await recommendNewsAction()
      break
    case 'unrecommend':
      await unrecommendNewsAction()
      break
    case 'duplicate':
      duplicateNews()
      break
    case 'delete':
      await deleteNewsAction()
      break
  }
}

// 发布新闻
const publishNewsAction = async () => {
  try {
    await publishNews(news.value.id)
    news.value.status = 'published'
    ElMessage.success('新闻发布成功')
    loadOperationLogs()
  } catch (error) {
    console.error('发布新闻失败:', error)
    ElMessage.error('发布新闻失败')
  }
}

// 撤回新闻
const unpublishNewsAction = async () => {
  try {
    await unpublishNews(news.value.id)
    news.value.status = 'draft'
    ElMessage.success('新闻撤回成功')
    loadOperationLogs()
  } catch (error) {
    console.error('撤回新闻失败:', error)
    ElMessage.error('撤回新闻失败')
  }
}

// 置顶新闻
const topNewsAction = async () => {
  try {
    await topNews(news.value.id)
    news.value.isTop = true
    ElMessage.success('新闻置顶成功')
    loadOperationLogs()
  } catch (error) {
    console.error('置顶新闻失败:', error)
    ElMessage.error('置顶新闻失败')
  }
}

// 取消置顶
const untopNewsAction = async () => {
  try {
    await untopNews(news.value.id)
    news.value.isTop = false
    ElMessage.success('取消置顶成功')
    loadOperationLogs()
  } catch (error) {
    console.error('取消置顶失败:', error)
    ElMessage.error('取消置顶失败')
  }
}

// 推荐新闻
const recommendNewsAction = async () => {
  try {
    await recommendNews(news.value.id)
    news.value.isRecommend = true
    ElMessage.success('新闻推荐成功')
    loadOperationLogs()
  } catch (error) {
    console.error('推荐新闻失败:', error)
    ElMessage.error('推荐新闻失败')
  }
}

// 取消推荐
const unrecommendNewsAction = async () => {
  try {
    await unrecommendNews(news.value.id)
    news.value.isRecommend = false
    ElMessage.success('取消推荐成功')
    loadOperationLogs()
  } catch (error) {
    console.error('取消推荐失败:', error)
    ElMessage.error('取消推荐失败')
  }
}

// 删除新闻
const deleteNewsAction = async () => {
  try {
    await ElMessageBox.confirm('确认要删除此新闻吗？此操作不可逆！', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteNews(news.value.id)
    ElMessage.success('新闻删除成功')
    router.push('/news')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除新闻失败:', error)
      ElMessage.error('删除新闻失败')
    }
  }
}

// 评论操作
const handleCommentSelection = (selection) => {
  selectedComments.value = selection.map(item => item.id)
}

const approveComment = async (comment) => {
  try {
    await apiApproveComment(comment.id)
    comment.status = 'approved'
    ElMessage.success('评论审核通过')
  } catch (error) {
    console.error('审核评论失败:', error)
    ElMessage.error('审核评论失败')
  }
}

const rejectComment = async (comment) => {
  try {
    await apiRejectComment(comment.id)
    comment.status = 'rejected'
    ElMessage.success('评论已拒绝')
  } catch (error) {
    console.error('拒绝评论失败:', error)
    ElMessage.error('拒绝评论失败')
  }
}

const deleteComment = async (comment) => {
  try {
    await ElMessageBox.confirm('确认要删除此评论吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await apiDeleteComment(comment.id)
    loadComments()
    ElMessage.success('评论删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评论失败:', error)
      ElMessage.error('删除评论失败')
    }
  }
}

const batchDeleteComments = async () => {
  try {
    await ElMessageBox.confirm(`确认要删除选中的 ${selectedComments.value.length} 条评论吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 批量删除评论的API调用
    loadComments()
    ElMessage.success('批量删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

const refreshComments = () => {
  loadComments()
}

// 其他操作
const editNews = () => {
  router.push(`/news/edit/${news.value.id}`)
}

const duplicateNews = () => {
  router.push(`/news/duplicate/${news.value.id}`)
}

const viewRelatedNews = (newsId) => {
  router.push(`/news/detail/${newsId}`)
}

// 工具函数
const getStatusType = (status) => {
  const typeMap = {
    'published': 'success',
    'draft': 'warning',
    'archived': 'info'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'published': '已发布',
    'draft': '草稿',
    'archived': '已归档'
  }
  return textMap[status] || '未知'
}

const getCommentStatusType = (status) => {
  const typeMap = {
    'approved': 'success',
    'pending': 'warning',
    'rejected': 'danger'
  }
  return typeMap[status] || 'info'
}

const getCommentStatusText = (status) => {
  const textMap = {
    'approved': '已通过',
    'pending': '待审核',
    'rejected': '已拒绝'
  }
  return textMap[status] || '未知'
}

// 返回
const goBack = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.news-detail-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
    
    h1 {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .header-right {
    display: flex;
    gap: 12px;
  }
}

.news-article {
  .article-header {
    margin-bottom: 24px;
    
    .article-title {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
      margin: 0 0 16px 0;
      line-height: 1.4;
    }
    
    .article-meta {
      display: flex;
      gap: 16px;
      align-items: center;
      flex-wrap: wrap;
      
      span {
        color: #606266;
        font-size: 14px;
      }
    }
  }
  
  .article-cover {
    margin-bottom: 24px;
    
    img {
      width: 100%;
      max-height: 400px;
      object-fit: cover;
      border-radius: 8px;
    }
  }
  
  .article-summary {
    margin-bottom: 24px;
    padding: 16px;
    background-color: #f8f9fa;
    border-radius: 8px;
    
    h3 {
      margin: 0 0 12px 0;
      font-size: 16px;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #606266;
      line-height: 1.6;
    }
  }
  
  .article-content {
    margin-bottom: 24px;
    line-height: 1.8;
    color: #303133;
    
    :deep(img) {
      max-width: 100%;
      height: auto;
      border-radius: 4px;
    }
  }
  
  .article-tags {
    h3 {
      margin: 0 0 12px 0;
      font-size: 16px;
      color: #303133;
    }
  }
}

.comments-management {
  .comments-toolbar {
    display: flex;
    gap: 12px;
    margin-bottom: 16px;
  }
  
  .user-info {
    display: flex;
    align-items: center;
    gap: 8px;
  }
}

.stats-list {
  .stat-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
    
    .stat-label {
      color: #606266;
    }
    
    .stat-value {
      color: #303133;
      font-weight: 500;
    }
  }
}

.news-info {
  .info-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
    
    .label {
      color: #606266;
      font-size: 14px;
    }
    
    .value {
      color: #303133;
      font-size: 14px;
    }
  }
}

.related-news {
  .related-item {
    display: flex;
    gap: 12px;
    padding: 8px 0;
    cursor: pointer;
    
    &:hover {
      background-color: #f8f9fa;
    }
    
    .related-cover {
      width: 60px;
      height: 40px;
      object-fit: cover;
      border-radius: 4px;
    }
    
    .related-info {
      flex: 1;
      
      .related-title {
        font-size: 14px;
        color: #303133;
        margin-bottom: 4px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .related-time {
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

.operation-logs {
  .log-content {
    .log-action {
      font-weight: 500;
      color: #303133;
      margin-bottom: 4px;
    }
    
    .log-operator {
      font-size: 12px;
      color: #606266;
    }
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    
    .header-left {
      width: 100%;
      justify-content: space-between;
    }
  }
  
  .article-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .comments-toolbar {
    flex-direction: column;
  }
  
  .related-item {
    flex-direction: column;
    
    .related-cover {
      width: 100%;
      height: 120px;
    }
  }
}
</style>
